using System;
using System.Collections.Generic;
using csvviewer.contracts;

namespace csvviewer.logic
{
	public class Calc_index_of_first_line_of_page : IDependsOn<ConcurrentList<long>>
	{
		private int _currentPageTopIndex = 1;
		
		public void Process(PageDirections direction)
		{
			switch(direction)
			{
			case PageDirections.First: 
				_currentPageTopIndex = 1;
				break;
			case PageDirections.Last:
				_currentPageTopIndex = Calc_last_page_top_index ();
				break;
			case PageDirections.Next:
				_currentPageTopIndex += _pageLength;
				if (_currentPageTopIndex >= _lineBuffer.Count)
					_currentPageTopIndex = Calc_last_page_top_index();
				break;
			case PageDirections.Previous:
				_currentPageTopIndex -= _pageLength;
				if (_currentPageTopIndex < 1)
					_currentPageTopIndex = 1;
				break;
			}
					
			this.Result(new Tuple<int,int, PageInfo>(_currentPageTopIndex, _pageLength, Calc_pageInfo(_currentPageTopIndex, _pageLength, _lineBuffer.Count))); 
		}
		
		
		public void Process(int pageNo)
		{
			_currentPageTopIndex = (pageNo-1) * _pageLength + 1;
			
			if (_currentPageTopIndex < 1) _currentPageTopIndex = 1;
			if (_currentPageTopIndex >= _lineBuffer.Count) _currentPageTopIndex = Calc_last_page_top_index();
			
			this.Result(new Tuple<int,int, PageInfo>(_currentPageTopIndex, _pageLength, Calc_pageInfo(_currentPageTopIndex, _pageLength, _lineBuffer.Count)));
		}
		
		
        private int _pageLength;
        public void Config(int pageLength)
        {
            _pageLength = pageLength;
        }
			
		
		public event Action<Tuple<int,int, PageInfo>> Result;
		
		
        private ConcurrentList<long> _lineBuffer;

        public void Inject(ConcurrentList<long> dependency)
        {
            _lineBuffer = dependency;
        }
		
		
		int Calc_last_page_top_index ()
		{
			return (_lineBuffer.Count-1) / _pageLength * _pageLength+1;
		}
		
		
		PageInfo Calc_pageInfo(int currentPageTopIndex, int pageLength, int linesInFile)
		{
			return new PageInfo{
									NumberOfFirstLine = currentPageTopIndex,
									PageNo = currentPageTopIndex / pageLength + 1, 
								 	NumberOfPages = (linesInFile-1) / pageLength + ((linesInFile-1) % pageLength == 0 ? 0 : 1)
							   };
		}
	}
}

